# 作者：20242321汤泽鹏
# 地点：电科院
# 时间：4 a.m
# 代理地址：Los Angels

import requests
import re
import smtplib
from email.mime.text import MIMEText
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
from email.mime.multipart import MIMEMultipart

def get_ctftime_upcoming(url):
    url_event = "https://ctftime.org/event/" #每个赛事的网址都是url_event+xxxx

    #下面寻找xxxx
    ua = UserAgent()
    headers = {
        'User-Agent': ua.random  # 每次随机生成一个合法的 User-Agent
    }
    r = requests.get(url, headers=headers)
    bs_url = BeautifulSoup(r.content, 'html.parser') #听说lxml更快？
    ctf_come = bs_url.find_all('table', class_='table table-striped upcoming-events') #因为在网页中选中class_='table table-striped upcoming-events'是赛事区域

    #接下来寻找每个event后面的4位数字
    #调试以后发现数字在<a标签后面
    #print(ctf_come)

    events = []
    for table_come in ctf_come:
        for a_come in table_come.find_all('a'):
            #print(a_come)
            href = a_come.get('href')
            if href and href.startswith('/event'):
                event_id = href.split('/')[-1]
                if event_id.isdigit():
                    #print(event_id)
                    new_url = url_event + event_id
                    # print(get_name(new_url)+" | "+get_time(new_url)+" | "+get_url(new_url))
                    # print(get_name(new_url) + " | " + get_time(new_url))
                    events.append({
                        'name':get_name(new_url),
                        'time':get_time(new_url),
                        'url':get_url(new_url),
                    })
    # for i in events:
    #     print(i)
    return events


def get_name(url):
    ua = UserAgent()
    headers = {
        'User-Agent': ua.random  # 每次随机生成一个合法的 User-Agent
    }
    r = requests.get(url, headers=headers)
    bs_url = BeautifulSoup(r.content, 'html.parser')  # 听说lxml更快？
    name = bs_url.find_all('h2')
    #print(name)#，结果是[<h2>Cyshock - The Awakening</h2>]
    #这里需要提取名字
    for h2_name in name:
        final_name = h2_name.get_text(strip=True)
        # print(final_name)
        return final_name

def get_time(url):
    ua = UserAgent()
    headers = {
        'User-Agent': ua.random
    }
    r = requests.get(url, headers=headers)
    bs_url = BeautifulSoup(r.content, 'html.parser')
    time = bs_url.find('div',class_ = 'span10')
    p_time = time.find('p')
    final_time = p_time.get_text(separator=' ', strip=True)
    return final_time

def get_url(url):
    ua = UserAgent()
    headers = {
        'User-Agent': ua.random
    }
    r = requests.get(url, headers=headers)
    bs_url = BeautifulSoup(r.content, 'html.parser')
    url = bs_url.find('div',class_ = 'span10')
    for p_url in bs_url.find_all('p'):
        # print(p_url)
        text = p_url.get_text(strip=True)
        #print(text)
        if text.startswith('Official URL:'):
            # print(text)
            return text

def send_mail_upcoming():
    # 获取赛事数据
    url = "https://ctftime.org/"
    events = get_ctftime_upcoming(url)

    # 构建 HTML 表格行
    table_rows = ""
    for event in events:
        table_rows += f"""
        <tr>
            <td>{event['name']}</td>
            <td>{event['time']}</td>
            <td>{event['url']}</td>
        </tr>
        """

    # 构建完整 HTML 内容
    html_template = """
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>CTF 赛事通知</title>
    </head>
    <body>
        <h1>即将开始的 CTF 赛事</h1>
        <table border="1" cellspacing="0" cellpadding="5" style="border-collapse: collapse;">
            <thead>
                <tr>
                    <th>赛事名称</th>
                    <th>时间</th>
                    <th>链接</th>
                </tr>
            </thead>
            <tbody>
                {table_rows}
            </tbody>
        </table>
    </body>
    </html>
    """
    html_content = html_template.format(table_rows=table_rows)

    # 发送邮件
    mail_host = "smtp.qq.com"
    mail_sender = "1397994670@qq.com"
    mail_pwd = ""

    smtp = smtplib.SMTP_SSL(mail_host, 465, local_hostname='localhost')
    smtp.login(mail_sender, mail_pwd)

    msg = MIMEMultipart()
    msg.attach(MIMEText(html_content, "html", "utf-8"))
    msg["Subject"] = "今日CTF赛事"
    msg["From"] = mail_sender
    receivers = ["571014006@qq.com", "1397994670@qq.com"]
    msg["To"] = ";".join(receivers)

    smtp.sendmail(mail_sender, receivers, msg.as_string())
    smtp.quit()
    print("邮件发送成功")

url="https://ctftime.org/"
# get_ctftime_upcoming(url)
# get_name(url)
# get_time(url)
# get_official_url(url)
# get_url(url)
send_mail_upcoming()
# get_ctftime_running(url)